<?php
namespace App\Model;

use App\Repository\Sys\Db;
use App\Repository\Common\ConstTable;
use App\Repository\Sys\JsonRespose;
use App\Repository\Sys\Str;
use EasyWeChat\Foundation\Application;

class OrderTable
{
    use Db;
    static private $table = 'order';

    //获取团队订单数和胜率
    static public function getOrderCount($team_id)
    {


        $where = "order.status=2 and pay_type=2 and order_type in(1,2) and (invite_team.team_id={$team_id} or invite_team.join_team_id={$team_id})";


        $count = \DB::select("select count(*) as c  from `order` LEFT JOIN invite_team ON invite_team.id=`order`.object_id   WHERE  {$where}", [])[0]->c;

     
        return ['count' => $count, 'win' => TeamTable::getWin($team_id)]; // 靠谱率 确认
    }


    //获取六个状态
    static public function status($type, $order_type, $pay_type, $is_comment, $status, $day_time = '')
    {
        $s = 1;
        if ($order_type == 3 and $pay_type == 2 and $status == 2 and $day_time > time()) {  //已订场
            $s = 1;
        } elseif ($pay_type == 3) {  //已取消
            $s = 5;
        } elseif ($pay_type == 2 and $status == 2 and $day_time < time()) { //已完成
            $s = 3;
        } elseif (in_array($order_type, [1, 2]) and $pay_type == 2 and $status == 2) { //已匹配
            $s = 2;
        } elseif ($pay_type == 2 and $status == 2 and $is_comment == 2) { //待评价
            $s = 4;
        } elseif (in_array($order_type, [1, 2]) and $pay_type == 2 and $status == 1) {  //未匹配
            $s = 6;
        }

        if ($type == 4) {
            $s = 4;
        }


//var_dump($day_time);die;
        //过了时间转变成待评价
//        if($s==2 and $day_time<time()){
//            $s=4;
//        }

        return $s;
    }

    //订单双方团队信息
    static public function team_info($object_id, $order_id = 0)
    {
        //['master' => ['name' => 'xx', 'img' => 'xxx', 'colour' => ''], 'slave' => ['name' => 'xx', 'img' => 'xxx', 'colour' => '']];
        $invite = InviteTeamTable::ORM()->where('id', $object_id)->first();
        $team = TeamTable::getTeamInfo($invite->team_id);


        $comment = CommentTable::ORM()->where('team_id', $team->id)->where('order_id', $order_id)->limit(10)->get();
        $com = [];
        foreach ($comment as $v) {
            $com[] = [
                'content' => $v->content,
                'content_num' => $v->content_num
            ];
        }
        $team_info['master'] = [
            'img' => $team->img,
            'name' => $team->name,
            'join_num' => $invite->join_num,
            'avg_age' => $invite->avg_age,
            'colour' => $invite->colour,
            'desc' => $invite->desc,
            'comment' => $com,
        ];
        if ($invite->join_team_id) {
            $team = TeamTable::getTeamInfo($invite->join_team_id);

            $comment = CommentTable::ORM()->where('team_id', $team->id)->where('order_id', $order_id)->limit(10)->get();
            $com = [];
            foreach ($comment as $v) {
                $com[] = [
                    'content' => $v->content,
                    'content_num' => $v->content_num
                ];
            }
            $team_info['slave'] = [
                'img' => $team->img,
                'name' => $team->name,
                'join_num' => $invite->slave_join_num,
                'avg_age' => $invite->slave_avg_age,
                'colour' => $invite->slave_colour,
                'desc' => $invite->slave_desc,
                'comment' => $com,
            ];
        } else {
            $team_info['slave'] = [];
        }
        return $team_info;
    }

    static public function orderBack($order_id)
    {

        $order = OrderTable::ORM()->where('order_id', $order_id)->first();

        $user = UserTable::ORM()->where('id', $order->uid)->first();

        UserLevelSetTable::updateLevel($order->uid, (int)($user->integral - $order->money));  //更新会员等级与积分

        //update order ing
        $app = new Application(config('app.weixin_options'));
        $payment = $app->payment;


        //查询退款  4200000058201803052927260160
//        $result = $payment->queryRefundByTransactionId($order->weixin_sn);
//        var_dump($result);
//        die;

        //退款
        $result = $payment->refund('ORDER_' . $order_id, date('Ymd') . $order->order_id, bcmul($order->money, 100, 0)); // 总金额 100 退款 100，操作员：商户号

        \Log::info("订单号:{$order_id}退款返回数据:".json_encode($result));

        if($result->result_code=='FAIL'){
            \Log::error($result->err_code_des);

            return JsonRespose::jsonArray(0, [],$result->err_code_des);
        }


        OrderTable::ORM()->where('order_id', $order_id)->update(['pay_type' => 3, 'status' => 3]);

        if($order->order_type==1){
            InviteTeamTable::ORM()->where('id',$order->object_id)->update(['status'=>4]);
        }
        //只有主队有退款操作  ,当没成团之前  已确认

        if ($order->coupon_id) { //派发逻辑
            $coupon = CouponTable::ORM()->where('id', $order->coupon_id)->first();

            $res = CouponListTable::ORM()->where('uid', $order->uid)->where('coupon_id', $order->coupon_id)->first();
            if ($res) {
                $res = CouponListTable::ORM()->where('uid', $order->uid)->where('coupon_id', $order->coupon_id)->increment('number',1);
            } else {
                $res = CouponListTable::ORM()->insert(
                    [
                        'money' => $coupon->money,
                        'name' => $coupon->name,
                        'start_time' => $coupon->start_time,
                        'end_time' => $coupon->end_time,
                        'uid' => $order->uid,
                        'dateline' => time(),
                        'number' => 1,
                        'coupon_id' => $order->coupon_id
                    ]);
            }
        }



        //恢复时间段
        $s = TimeBlockTable::ORM()->where('order_id', $order_id)->delete();
        return JsonRespose::jsonArray(1, $result);

    }

}